// 用户列表
import React, { useState, useEffect } from "react";
import { Table } from "antd";

import { findUser } from "@/api/UserApi";

const columns = [
  {
    title: "用户Id",
    dataIndex: "id"
  },
  {
    title: "用户名",
    dataIndex: "username"
  },
  {
    title: "用户性别",
    dataIndex: "gender",
    render(col, row) {
      if (row.gender === 1) {
        return "男";
      } else {
        return "女";
      }
    }
  }
];

const UserManageList = () => {
  // 用户列表
  const [userList, setUserList] = useState([]);
  // 每页显示条数
  const [limit, setLimit] = useState(10);
  // 总的条数
  const [total, setTotal] = useState(1);
  // loading
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 默认调用一次
    getUserList(1);
  }, []);

  /**
   * 页码改变时再执行获取用户列表
   */
  const onChange = (page, pageSize) => {
    getUserList(page);
  };

  /**
   * 获取用户列表
   */
  const getUserList = page => {
    // 加载中...
    setLoading(true);

    findUser({ _page: page, _limit: limit }).then(response => {
      const { data, headers } = response;

      setUserList(data);
      setTotal(parseInt(headers["x-total-count"]));

      // 加载完成...
      setLoading(false);
    });
  };

  return (
    <div className="page-user-list">
      <h1>用户列表</h1>

      <Table
        rowKey="id"
        columns={columns}
        dataSource={userList}
        loading={loading}
        pagination={{
          total: total,
          defaultPageSize: limit,
          onChange: onChange
        }}
      ></Table>
    </div>
  );
};

export default UserManageList;
